//
//  HeightPickerView.m
//  jinritoutiao
//
//  Created by 汤环 on 2025/11/7.
//

#import "HeightPickerView.h"
#import <AudioToolbox/AudioToolbox.h>

/// 每个刻度的间距（单位：pt）
static const CGFloat kScaleSpacing = 8.0;

/// 刻度线宽度
static const CGFloat kScaleLineWidth = 1.0;

/// 短刻度线高度
static const CGFloat kShortScaleHeight = 8.0;

/// 中刻度线高度（每5cm）
static const CGFloat kMiddleScaleHeight = 12.0;

/// 长刻度线高度（每10cm）
static const CGFloat kLongScaleHeight = 20.0;

@interface HeightPickerView () <UIScrollViewDelegate>

/// 滚动视图
@property (nonatomic, strong) UIScrollView *scrollView;

/// 刻度尺容器视图
@property (nonatomic, strong) UIView *scaleContentView;

/// 中心指示器视图
@property (nonatomic, strong) UIView *centerIndicatorView;

/// 显示当前身高值的标签
@property (nonatomic, strong) UILabel *valueLabel;

/// 上次触发震动的身高值
@property (nonatomic, assign) NSInteger lastFeedbackHeight;

/// 触觉反馈生成器（iOS 10+）
@property (nonatomic, strong) UIImpactFeedbackGenerator *feedbackGenerator API_AVAILABLE(ios(10.0));

@end

@implementation HeightPickerView

#pragma mark - 初始化方法

- (instancetype)initWithFrame:(CGRect)frame initialHeight:(NSInteger)initialHeight {
    self = [super initWithFrame:frame];
    if (self) {
        _minHeight = 100;
        _maxHeight = 200;
        _currentHeight = initialHeight;
        _scaleLineColor = [UIColor lightGrayColor];
        _indicatorColor = [UIColor systemBlueColor];
        _lastFeedbackHeight = initialHeight;
        
        [self setupUI];
        [self scrollToHeight:initialHeight animated:NO];
        
        // 初始化触觉反馈生成器
        if (@available(iOS 10.0, *)) {
            _feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
            [_feedbackGenerator prepare];
        }
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame initialHeight:170];
}

#pragma mark - UI 设置

- (void)setupUI {
    self.backgroundColor = [UIColor whiteColor];
    
    // 创建滚动视图
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.delegate = self;
    self.scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
    [self addSubview:self.scrollView];
    
    // 创建刻度尺容器
    [self setupScaleContentView];
    
    // 创建中心指示器
    [self setupCenterIndicator];
    
    // 创建数值显示标签
    [self setupValueLabel];
}

/// 设置刻度尺容器视图
- (void)setupScaleContentView {
    NSInteger totalScales = self.maxHeight - self.minHeight + 1;
    CGFloat contentWidth = totalScales * kScaleSpacing;
    CGFloat leftPadding = CGRectGetWidth(self.bounds) / 2.0;
    
    self.scaleContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, contentWidth + leftPadding * 2, CGRectGetHeight(self.bounds))];
    self.scaleContentView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:self.scaleContentView];
    
    self.scrollView.contentSize = CGSizeMake(contentWidth + leftPadding * 2, 0);
    
    // 绘制刻度线
    [self drawScaleLines];
}

/// 绘制刻度线
- (void)drawScaleLines {
    CGFloat centerY = CGRectGetHeight(self.scaleContentView.bounds) / 2.0;
    CGFloat leftPadding = CGRectGetWidth(self.bounds) / 2.0;
    
    for (NSInteger i = self.minHeight; i <= self.maxHeight; i++) {
        NSInteger index = i - self.minHeight;
        CGFloat xPosition = leftPadding + index * kScaleSpacing;
        
        // 确定刻度线高度和宽度
        CGFloat scaleHeight = kShortScaleHeight;
        CGFloat lineWidth = kScaleLineWidth;
        BOOL shouldShowLabel = NO;
        
        if (i % 10 == 0) {
            // 每10cm一个长刻度
            scaleHeight = kLongScaleHeight;
            lineWidth = 2.0;
            shouldShowLabel = YES;
        } else if (i % 5 == 0) {
            // 每5cm一个中刻度
            scaleHeight = kMiddleScaleHeight;
            lineWidth = 1.5;
        }
        
        // 创建刻度线
        UIView *scaleLine = [[UIView alloc] initWithFrame:CGRectMake(xPosition - lineWidth/2, centerY - scaleHeight/2, lineWidth, scaleHeight)];
        scaleLine.backgroundColor = self.scaleLineColor;
        [self.scaleContentView addSubview:scaleLine];
        
        // 添加数字标签（每10cm）
        if (shouldShowLabel) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPosition - 20, centerY + scaleHeight/2 + 5, 40, 20)];
            label.text = [NSString stringWithFormat:@"%ld", (long)i];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont systemFontOfSize:12];
            label.textColor = self.scaleLineColor;
            [self.scaleContentView addSubview:label];
        }
    }
}

/// 设置中心指示器
- (void)setupCenterIndicator {
    CGFloat centerX = CGRectGetWidth(self.bounds) / 2.0;
    CGFloat indicatorHeight = 40.0;
    CGFloat centerY = CGRectGetHeight(self.bounds) / 2.0;
    
    self.centerIndicatorView = [[UIView alloc] initWithFrame:CGRectMake(centerX - 1, centerY - indicatorHeight/2, 2, indicatorHeight)];
    self.centerIndicatorView.backgroundColor = self.indicatorColor;
    self.centerIndicatorView.layer.cornerRadius = 1;
    [self addSubview:self.centerIndicatorView];
    
    // 添加顶部和底部的三角形装饰
    [self addTriangleToIndicator];
}

/// 添加三角形装饰到指示器
- (void)addTriangleToIndicator {
    CGFloat triangleSize = 8.0;
    CGFloat centerX = CGRectGetWidth(self.bounds) / 2.0;
    CGFloat centerY = CGRectGetHeight(self.bounds) / 2.0;
    
    // 顶部三角形
    UIBezierPath *topTrianglePath = [UIBezierPath bezierPath];
    [topTrianglePath moveToPoint:CGPointMake(centerX, centerY - 20 - triangleSize)];
    [topTrianglePath addLineToPoint:CGPointMake(centerX - triangleSize/2, centerY - 20)];
    [topTrianglePath addLineToPoint:CGPointMake(centerX + triangleSize/2, centerY - 20)];
    [topTrianglePath closePath];
    
    CAShapeLayer *topTriangleLayer = [CAShapeLayer layer];
    topTriangleLayer.path = topTrianglePath.CGPath;
    topTriangleLayer.fillColor = self.indicatorColor.CGColor;
    [self.layer addSublayer:topTriangleLayer];
    
    // 底部三角形
    UIBezierPath *bottomTrianglePath = [UIBezierPath bezierPath];
    [bottomTrianglePath moveToPoint:CGPointMake(centerX, centerY + 20 + triangleSize)];
    [bottomTrianglePath addLineToPoint:CGPointMake(centerX - triangleSize/2, centerY + 20)];
    [bottomTrianglePath addLineToPoint:CGPointMake(centerX + triangleSize/2, centerY + 20)];
    [bottomTrianglePath closePath];
    
    CAShapeLayer *bottomTriangleLayer = [CAShapeLayer layer];
    bottomTriangleLayer.path = bottomTrianglePath.CGPath;
    bottomTriangleLayer.fillColor = self.indicatorColor.CGColor;
    [self.layer addSublayer:bottomTriangleLayer];
}

/// 设置数值显示标签
- (void)setupValueLabel {
    self.valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.bounds), 40)];
    self.valueLabel.textAlignment = NSTextAlignmentCenter;
    self.valueLabel.font = [UIFont boldSystemFontOfSize:32];
    self.valueLabel.textColor = self.indicatorColor;
    self.valueLabel.text = [NSString stringWithFormat:@"%ld cm", (long)self.currentHeight];
    [self addSubview:self.valueLabel];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 计算当前对应的身高值
    CGFloat leftPadding = CGRectGetWidth(self.bounds) / 2.0;
    CGFloat offsetX = scrollView.contentOffset.x - leftPadding;
    NSInteger height = self.minHeight + (NSInteger)round(offsetX / kScaleSpacing);
    
    // 限制范围
    height = MAX(self.minHeight, MIN(self.maxHeight, height));
    
    if (height != self.currentHeight) {
        self.currentHeight = height;
        self.valueLabel.text = [NSString stringWithFormat:@"%ld cm", (long)height];
        
        // 触发回调
        if (self.valueChangedBlock) {
            self.valueChangedBlock(height);
        }
        
        // 触发触觉反馈
        [self triggerHapticFeedback];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self snapToNearestValue];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self snapToNearestValue];
}

#pragma mark - 私有方法

/// 滚动到指定身高
/// @param height 目标身高值
/// @param animated 是否动画
- (void)scrollToHeight:(NSInteger)height animated:(BOOL)animated {
    height = MAX(self.minHeight, MIN(self.maxHeight, height));
    
    CGFloat leftPadding = CGRectGetWidth(self.bounds) / 2.0;
    NSInteger index = height - self.minHeight;
    CGFloat targetOffsetX = index * kScaleSpacing + leftPadding;
    
    [self.scrollView setContentOffset:CGPointMake(targetOffsetX, 0) animated:animated];
    
    self.currentHeight = height;
    self.valueLabel.text = [NSString stringWithFormat:@"%ld cm", (long)height];
}

/// 吸附到最近的整数值
- (void)snapToNearestValue {
    [self scrollToHeight:self.currentHeight animated:YES];
}

/// 触发触觉反馈（震动）
- (void)triggerHapticFeedback {
    // 只有当身高值变化时才触发
    if (self.currentHeight != self.lastFeedbackHeight) {
        self.lastFeedbackHeight = self.currentHeight;
        
        // iOS 10+ 使用触觉反馈
        if (@available(iOS 10.0, *)) {
            [self.feedbackGenerator impactOccurred];
            [self.feedbackGenerator prepare];
        } else {
            // iOS 10以下使用系统震动
            AudioServicesPlaySystemSound(1519); // Peek feedback
        }
    }
}

#pragma mark - Setter

- (void)setCurrentHeight:(NSInteger)currentHeight {
    if (_currentHeight != currentHeight) {
        _currentHeight = currentHeight;
        self.valueLabel.text = [NSString stringWithFormat:@"%ld cm", (long)currentHeight];
    }
}

- (void)setScaleLineColor:(UIColor *)scaleLineColor {
    _scaleLineColor = scaleLineColor;
    // 重新绘制刻度线
    for (UIView *subview in self.scaleContentView.subviews) {
        [subview removeFromSuperview];
    }
    [self drawScaleLines];
}

- (void)setIndicatorColor:(UIColor *)indicatorColor {
    _indicatorColor = indicatorColor;
    self.centerIndicatorView.backgroundColor = indicatorColor;
    self.valueLabel.textColor = indicatorColor;
}

#pragma mark - 布局

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 更新滚动视图frame
    self.scrollView.frame = self.bounds;
    
    // 重新计算内容视图大小
    NSInteger totalScales = self.maxHeight - self.minHeight + 1;
    CGFloat contentWidth = totalScales * kScaleSpacing;
    CGFloat leftPadding = CGRectGetWidth(self.bounds) / 2.0;
    
    self.scaleContentView.frame = CGRectMake(0, 0, contentWidth + leftPadding * 2, CGRectGetHeight(self.bounds));
    self.scrollView.contentSize = CGSizeMake(contentWidth + leftPadding * 2, 0);
}

@end
